package wint.session.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wint.lang.WintException;
import wint.lang.utils.CollectionUtil;
import wint.lang.utils.StreamUtil;
import wint.session.data.cookie.CookieSessionStoreConfig;
import wint.session.data.cookie.CookieStoreSessionDataService;
import wint.session.serialize.StringSerializeService;
import wint.session.util.WintSessionContants;

public class DefaultSessionConfig implements SessionConfig {
	
	static final transient Logger log = LoggerFactory.getLogger(DefaultSessionConfig.class);
	
	static final String COOKIE_SESSION_ENCRYPT_KEY_FILENAME = "wint-session-key";

	static final String DEFAULT_COOKIE_SESSION_KEY = "default_key";
	
	/**
	 * 默认的session超时时间(秒)
	 */
	private int expire = WintSessionContants.WIN_COOKIE_SESSION_EXPIRE;
	
	private String sessionIdName = WintSessionContants.SESSION_ID_NAME;
	
	private List<SessionDataServiceConfig> sessionDataServiceConfigs = CollectionUtil.newArrayList();

	private CookieSessionStoreConfig cookieSessionStoreConfig = new CookieSessionStoreConfig();
	
	public void init() {
		SessionDataServiceConfig cookieSessionDataServiceConfig = new SessionDataServiceConfig();
		cookieSessionStoreConfig.setEncryptKey(loadCookieSessionKey());
		
		cookieSessionDataServiceConfig.setSessionStoreConfig(cookieSessionStoreConfig);
		cookieSessionDataServiceConfig.setSessionDataServiceClass(CookieStoreSessionDataService.class);
		cookieSessionDataServiceConfig.setSerializeService(new StringSerializeService());
		
		sessionDataServiceConfigs.add(cookieSessionDataServiceConfig);
	}
	
	private String loadCookieSessionKey() {
		InputStream is = WebResourceUtil.getWebResouceAsStream(COOKIE_SESSION_ENCRYPT_KEY_FILENAME);
		if (is == null) {
			log.warn("no wint-session-key file found, use default cookie session key!!!");
			return DEFAULT_COOKIE_SESSION_KEY;
		} else {
			try {
				return StreamUtil.readAsString(is);
			} catch (IOException e) {
				throw new WintException(e);
			}
		}
	}
	
	public int getExpire() {
		return expire;
	}

	public List<SessionDataServiceConfig> getSessionDataServiceConfigs() {
		return sessionDataServiceConfigs;
	}

	public String getSessionIdName() {
		return sessionIdName;
	}

	public void setExpire(int expire) {
		this.expire = expire;
	}

	public void setSessionIdName(String sessionIdName) {
		this.sessionIdName = sessionIdName;
	}

	public void setSessionDataServiceConfigs(List<SessionDataServiceConfig> sessionDataServiceConfigs) {
		this.sessionDataServiceConfigs = sessionDataServiceConfigs;
	}

}
